// pages/departmentCenter/departmentCenter.js

import * as echarts from '../../ec-canvas/echarts';

const app = getApp();
var echartCanvase, signEchartCanvas;
var chart;

// 折线图
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  console.log(width);
  console.log(height);
  canvas.setChart(chart);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    pieec:{},
    signpieec: {},
    departmentId:0,
    tempData: {
      hasUserInfo: 1,
      hasWeChatRun: 1,
      hasToken: true,
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      isUserIn: true,
    },
    ec: {
      onInit: initChart
    },
    weeksRank:[],

// 被选中天数的毫秒值，默认为当天
    todayTime:new Date().getTime(),
    weekData:{
      pjbs: 0,
      tjts: 0,
      pjqdts: 0,
      pjqdl: 0,
      pjyxrts: 0,
      pjyxrl: 0,
      zxObj:{},
    },
    monthData:{
      pjbs: 0,
      tjts: 0,
      pjqdts: 0,
      pjqdl: 0,
      pjyxrts: 0,
      pjyxrl: 0,
      zxObj: {},
    },

    //顶部选项卡
    navbar: ['个人排名', '单位数据'],
    currentTab: 0,

    //折线图选项卡
    lineNavbar: ['近一周', '近一月'],
    lineCurrentTab: 0,

    //今日本部排行选项卡
    ranking: ['今日排名', '本周排名', '本月排名'],
    rankcurrentTab: 0,

    departmentName: '正在加载',
    todaysRank: [],

    //日历
    days_style: [
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#000000' },
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#000000' },
      { month: 'current', day: 3, color: '#40B7E6' }
    ],

    // dayStepNum: "正在加载...",
    // dayRank: "...",
    // weekStepNum: "正在加载...",
    weekRank: "正在加载...",
    // monthStepNum: "正在加载...",
    monthRank: "正在加载...",

    indexToDepartRank: ""
  },
  echartInit(e) {
    echartCanvase = e;
    // initPieChart(e.detail.canvas, e.detail.width, e.detail.height);
  },
  signechartInit(e) {
    signEchartCanvas = e;
    // initSignPieChart(e.detail.canvas, e.detail.width, e.detail.height);
  },
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
  },
  lineNavbarTap: function (e) {
    this.setData({
      lineCurrentTab: e.currentTarget.dataset.idx
    });
    this.setZXchart();
  },
  rankingTap: function (e) {
    this.setData({
      rankcurrentTab: e.currentTarget.dataset.idx
    })
  },
  dateChange: function (event) {
    console.log(event.detail);
  },
  dayClick: function (event) {
    let _this = this;
    let clickDay = event.detail.day;
    let changeDay = "days_style["+1+"].day";
    let changeBg = "days_style["+1+"].background";
    _this.reviewThisPage(event.detail);
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#E5E5E5"
    })

  },
  // 修改封面
  changeFM(){
    wx.showModal({
      title:"温馨提示",
      content:"您的操作会直接修改部门封面，是否继续？",
      cancelText:"取消",
      confirmText:"继续修改",
      success(){
        console.log("aaa");
      }
    });
  },

  // 重新初始化数据视图
  reviewThisPage(_dateObj){
    let _this = this;
    let thisDate = new Date();
    thisDate.setFullYear(_dateObj.year);
    thisDate.setMonth(_dateObj.month-1);
    thisDate.setDate(_dateObj.day);
    
    wx.showLoading({
      title:"正在加载",
    });

    // 获取近一周部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(thisDate.getTime() - 6 * 24 * 60 * 60 * 1000), thisDate, function (_data) {
      console.log(_data);
      wx.hideLoading();
      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.department_day_step_num.length);
      _this.setData({
        weekData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.department_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
      wx.hideLoading();
    });

    // 获取近一月部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(thisDate.getTime() - 30 * 24 * 60 * 60 * 1000), thisDate, function (_data) {
      console.log(_data);
      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.department_day_step_num.length);

      _this.setData({
        monthData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.department_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
      wx.hideLoading();
    });

  },

  // 饼图
  initPieChart(canvas, width, height) {
    let _this = this;
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height
    });
    canvas.setChart(chart);

    var option = {
      backgroundColor: 'transparent',
      color: ["#FC8D52", "#48CFAE"],
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        textStyle: {
          fontSize: 16
        }
      },
      series: [{
        label: {
          normal: {
            position: 'inner',
            textStyle: {
              fontWeight: 300,
              fontSize: 16    //文字的字体大小
            },
            formatter: '{d}%'

          }
        },
        type: 'pie',
        center: ['25%', '55%'],
        radius: [0, '60%'],
        data: [{
          value: _this.data.topDepartmentStatisticsObj.department_num - _this.data.topDepartmentStatisticsObj.department_effective_day_num,
          name: '未达标人数'
        }, {
          value: _this.data.topDepartmentStatisticsObj.department_effective_day_num,
          name: '达标人数'
        }],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
    return chart;
  },

  initSignPieChart(canvas, width, height) {
    let _this = this;
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
    });
    canvas.setChart(chart);

    var option = {
      backgroundColor: 'transparent',
      color: ["#EC87BF", "#FFCE55"],
      tooltip: {
        show: true,
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        textStyle: {
          fontSize: 16
        }
      },
      series: [{
        label: {
          normal: {
            position: 'inner',
            textStyle: {
              fontWeight: 300,
              fontSize: 16    //文字的字体大小
            },
            formatter: '{d}%'
          }
        },
        legend: {
          textStyle: {
            fontSize: 14,
          }
        },
        type: 'pie',
        center: ['70%', '50%'],
        radius: [0, '60%'],
        data: [{
          value: _this.data.topDepartmentStatisticsObj.department_num - _this.data.topDepartmentStatisticsObj.sign_num,
          name: '未签到'
        }, {
          value: _this.data.topDepartmentStatisticsObj.sign_num,
          name: '已签到'
        }],

        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 2, 2, 0.3)'
          }
        }
      }]
    };

    chart.setOption(option);
    return chart;
  },

// 初始化折线图
  setZXchart(){
    let _this = this;
    let _obj = _this.data.lineCurrentTab == 0 ? _this.data.weekData.zxObj : _this.data.monthData.zxObj;
    let j = 0;
    j = _obj.dateArray ? _obj.dateArray.length : 0;
    // let yxrArray = [];
    // for (let i = 0; i < j;i++){
    //   yxrArray.push(10000);
    // }
    var option = {
      // color: ["#37A2DA", "#67E0E3", "#9FE6B8"],
      legend: {
        data: ['有效日步数', '当日平均步数'],
        top: 0,
        left: 'center',
        z: 100,
        textStyle: {
          fontSize: 16
        }
      },
      grid: {
        left: 350,
        right: -60,
        top: 200,
        bottom: -20
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        // data: ['01/28', '01/29', '01/30', '01/31', '02/01', '02/02', '02/03'],
        data: _obj.dateArray
        // show: false
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        scale: true,
        // show: false
      },
      series: [{
        name: '每日平均步数',
        type: 'line',
        data: _obj.dateStepArray
        // data: [8674, 9201, 12672, 14895, 7835, 16921, 16750]
      }]
    };
    if (chart && option){
      chart.setOption(option);
    }
  },

// 初始化页面
  initPageData(){
    console.log("开始初始化页面");
    let _this = this;
    // 获取今日部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId,new Date(),new Date(),function(_data){
      console.log(_data);
      _this.setData({
        topDepartmentStatisticsObj: _data,
        yxrdbl: Math.ceil(_data.department_effective_day_num / _data.department_num * 100),
        dbrjbs: _data.sign_num > 0 ? Math.ceil(_data.department_effective_step_num[0].step_number / _data.sign_num) : 0,
        qdl: Math.ceil(_data.sign_num / _data.department_num * 100)
      });
      //_this.initPieChart(echartCanvase.detail.canvas, echartCanvase.detail.width, echartCanvase.detail.height);
      //_this.initSignPieChart(signEchartCanvas.detail.canvas, signEchartCanvas.detail.width, signEchartCanvas.detail.height);

    });


    // 获取近一周部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(_this.data.todayTime - 6 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);

      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number ? item.step_number:0);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = _data.department_day_step_num.length?Math.ceil(pjbs / _data.department_day_step_num.length):0;
      _this.setData({
        weekData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: _data.department_day_step_num.length?Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100):0,
          pjyxrts: pjyxrts,
          pjyxrl: _data.department_day_step_num.length? Math.ceil(pjyxrts / _data.department_day_step_num.length * 100):0,
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
    });

    // 获取近一月部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(_this.data.todayTime - 30 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);

      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.department_day_step_num.length);

      _this.setData({
        monthData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.department_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
    });
    
    // 获取部门详情
    app.getDepartmentInfo(_this.data.departmentId,function(_data){
      console.log(_data);
      _this.setData({
        departmentName:_data.department_name,
        departmentFm: _data.dex_cover
      });
    });
    
    // 获取今日排名
    app.getUserRankListByDepartment(_this.data.departmentId,new Date(),new Date(),function(_data){
      console.log(_data);
      _this.setData({
        todaysRank: _data
      });

    });

    // 获取本周排名
    app.getUserRankListByDepartment(_this.data.departmentId, new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);
      _this.setData({
        weeksRank: _data
      });

      var userInfoPart = app.data.userInfo;
      console.log(userInfoPart);
      for (var i = 0; i < _data.length; i++) {
        if (_data[i].user_name == userInfoPart.guildUser.user_name) {
          _this.setData({
            weekRank: _data[i].rank,
          });
        }
      }

    });

    // 获取本月排名
    app.getUserRankListByDepartment(_this.data.departmentId, new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);
      _this.setData({
        monthsRank: _data
      });

      var userInfoPart = app.data.userInfo;
      console.log(userInfoPart);
      for (var i = 0; i < _data.length; i++) {
        if (_data[i].user_name == userInfoPart.guildUser.user_name) {
          _this.setData({
            monthRank: _data[i].rank,
          });
        }
      }

    });
 
  },

// 个人点击事件
  personClick(_e){
    wx.navigateTo({
      url: "/pages/personalDetail/personalDetail?phone=" + _e.currentTarget.dataset.phone,
      success() {
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    var userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo);
    _this.setData({
      userInfo: userInfo,
      departmentId: options.id,
      indexToDepartRank: options.num
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.commonOnLoad(this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})